<template>
    <div ref="overlayContainer" v-show="modelValue">
      <!-- 插槽：父组件可以传入任意模板内容 -->
      <slot :coordinate="currentCoordinate"></slot>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import Overlay from 'ol/Overlay';
import {nextTick} from 'vue'
// 定义组件属性
const props = defineProps({
  modelValue: Boolean, // 用于控制显示/隐藏，即 v-model
  position: Array,     // Overlay 的地理坐标 [x, y]
  map: Object,         // 父组件传入的 ol.Map 实例
  offset: {
    type: Array,
    default: () => [0, 0]
  },
  positioning: {
    type: String,
    default: 'bottom-center'
  }
});

// 定义 emits，用于更新 v-model
const emit = defineEmits(['update:modelValue']);
const overlayContainer = ref(null);
let overlay = null;
const currentCoordinate = ref(null);
// 监听 position 变化
watch(() => props.position, (newPos) => {
  if (newPos) {
    console.log('显示')
    currentCoordinate.value = newPos;
    overlay.setPosition(newPos);
  } else {
    overlay.setPosition(undefined);
  }
});

// 监听 modelValue 变化，同步 Overlay 的显示状态
watch(() => props.modelValue, (newVal) => {
  if (newVal && props.position) {
    overlay.setPosition(props.position);
  } else {
    overlay.setPosition(undefined);
  }
});
// 初始化 Overlay
onMounted(() => {

  nextTick(()=>{
    overlay = new Overlay({
      element: overlayContainer.value,
      offset: props.offset,
      positioning: props.positioning,
      stopEvent: false
    });

    console.log(overlay,'overlay')

    props.map.addOverlay(overlay);
  })


});

// 清理资源
onUnmounted(() => {
  if (overlay && props.map) {
    props.map.removeOverlay(overlay);
  }
});

// 提供一个关闭方法，可以从插槽内容中调用
const close = () => {
  emit('update:modelValue', false);
};

// 将方法暴露给父组件（可选）
defineExpose({
  close,
  setPosition: (coord) => { if(overlay) overlay.setPosition(coord); }
});
</script>